import Vue from 'vue'

Vue.directive('cml', {
  bind: function (el, binding, vnode) {
    const name = binding.value || vnode.child.$options.name,
      context = vnode.context
    if (context.$_hasPromission(name)) {
      el.dataset.permit = true
    } else {
      el.dataset.permit = false
    }
  },
  inserted: function (el, binding, vnode) {
    const name = binding.value || vnode.child.$options.name,
      context = vnode.context
    if (context.$_hasPromission(name)) {
      el.dataset.permit = true
    } else {
      el.dataset.permit = false
    }
  },
  update: function (el, binding, vnode, oldVnode) {
    const name = binding.value || vnode.child.$options.name,
      context = vnode.context
    if (context.$_hasPromission(name)) {
      el.dataset.permit = true
    } else {
      el.dataset.permit = false
    }
  },
  componentUpdated: function (el, binding, vnode, oldVnode) {},
  unbind: function (el, binding, vnode) {}
})

Vue.prototype.$_hasPromission = function (name) {
  let license = this.$store.state.cmlpanel.license
  // 所有权限
  if (typeof license === 'string' && license === 'all') {
    return true
  }
  // 指定权限
  let lic = null
  if (Array.isArray(license)) {
    lic = license.map((l) => {
      return l.toLowerCase()
    })
    return lic.includes(name.toLowerCase())
  } else {
    // fixme
    // return false
  }
}
